跳到主要内容

01设计模式

  • a、针对接口编程

  • b、优先使用组合,而不是继承。

  • c、 找到并封装变化点。

2、设计原则

高内聚、低耦合

a、 单一职责原则(SRP)

​ 不要存在多于一个导致类变更的原因。通俗的说,即一个类只

​ 负责一项职责。

b、 开闭原则(OCP)

​ 一个软件实体如类、模板和函数应该对扩展开放,对修改关闭

c、 依赖倒置原则(DIP)

​ 高层模块不应该依赖低层模块,二者都应该依赖其抽象;

​ 抽象不应该依赖细节;细节应该依赖抽象。

d、 接口隔离原则(ISP)

​ 客户端不应该依赖它不需要的接口;一个类对另一个类的依赖

​ 应该建立在最小的接口上。

e、 里氏替换原则(LSP)

如果对每一个类型为T1的对象O1,都有类型为T2的对象O2,使得以T1定义的所有程序P在所有的对象O1都代换成O2时,程序 P的行为没有发生变化,那么类型T2是类型T1的子类型。

所有引用基类的地方必须能透明地使用其子类的对象。

解决方案: 子类可以扩展父类的功能,但不能改变父类原有的功能。

  • a、子类可以增加自己特有的方法;

  • b、子类可以实现父类的抽象方法,但不能覆盖父类的非抽象方法。

#include <iostream>

//依赖倒置原则 Dependence Inversion Principle

using namespace std;

class Ireader
{
public:
virtual string getContents()=0;

};

class Book : public Ireader
{
public:
string getContents()
{
return "从前有座山,山里有个小和尚,";
}
};

class NewsPaper:public Ireader
{
public:
string getContents()
{
return "下一次再见 拜拜!";
}
};
class Mother
{
public:
void tellStory(Ireader *i)
{
cout<<i->getContents()<<endl;
}
};

int main(int argc, char *argv[])
{
Mother M;
Book *b=new Book;
NewsPaper *n=new NewsPaper;

cout<<"mother start to tell story"<<endl;
M.tellStory(b);

cout<<"mother start to tell news"<<endl;
M.tellStory(n);

delete b;
delete n;
return 0;
}

#include <iostream>
using namespace std;

//里氏替换原则LSP

class A
{
public :
int add(int a, int b)
{
return a + b;
}
};

class B :public A
{
public :
int add(int a, int b)
{
return a - b;
}
};

int main()
{
A a; B b;

cout << a.add(2, 3) << endl;
cout << b.add(2, 3) << endl;

return 0;
}